package com.alex.statistics.method.descriptive;
import com.alex.statistics.pojo.result.descriptive.DispersionResult;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.DoubleSummaryStatistics;

/**
 * 离散程度分析计算工具
 */
@Component
public class DispersionAnalyzer {

    /**
     * 计算离散程度指标
     * @param data 数据集
     * @return DispersionDo 包含标准差、方差、极差
     * @throws IllegalArgumentException 如果数据为空或null
     */
    public DispersionResult analyze(List<Double> data) {
        if (data == null || data.isEmpty()) {
            throw new IllegalArgumentException("数据不能为空");
        }

        // 计算平均值
        double mean = calculateMean(data);

        // 计算方差
        double variance = calculateVariance(data, mean);

        // 计算标准差
        double stdDev = Math.sqrt(variance);

        // 计算极差
        DoubleSummaryStatistics stats = data.stream()
                .mapToDouble(Double::doubleValue)
                .summaryStatistics();
        double range = stats.getMax() - stats.getMin();

        return new DispersionResult(stdDev, variance, range);
    }

    private   double calculateMean(List<Double> data) {
        return data.stream()
                .mapToDouble(Double::doubleValue)
                .average()
                .orElse(0.0);
    }

    private   double calculateVariance(List<Double> data, double mean) {
        return data.stream()
                .mapToDouble(x -> Math.pow(x - mean, 2))
                .average()
                .orElse(0.0);
    }
}